package com.tanqidi.arcgisandroid.di

import android.content.Context
import com.google.gson.*
import com.tanqidi.arcgisandroid.R
import com.tanqidi.arcgisandroid.base.converter.LenientGsonConverterFactory
import com.tanqidi.arcgisandroid.base.utils.RxUtils
import com.tanqidi.arcgisandroid.base.utils.getString
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

/**
 * global dependence
 */
@Module
@InstallIn(SingletonComponent::class)
class AppModule {
    companion object {
        val okHttpClient = OkHttpClient.Builder()
            .sslSocketFactory(RxUtils.createSSLSocketFactory())
            .hostnameVerifier(RxUtils.TrustAllHostnameVerifier())
            .connectTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(5, TimeUnit.SECONDS)
            .build()
    }

    @Provides
    @Singleton
    fun retrofit(@ApplicationContext context: Context): Retrofit {
        val gson = GsonBuilder().create()
        return Retrofit.Builder()
            .baseUrl(getString(R.string.base_url))
            .client(okHttpClient)
            .addConverterFactory(LenientGsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
    }
}